//分享官账户
import React from 'react'
import { Modal, Form, Input, Button, Space, InputNumber, message } from "antd";
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheButton from '@/components/TheButton'
import TheQueryForm from '@/components/TheQueryForm';
import { sharerAccountPage, listByMemberId, addMonthlyReward } from '@/request/distribution/sharerAccount.js'
import store from "@/store/store"
import _ from 'lodash'
export default class SharerAccount extends React.Component {
  state = {
    searchOption: [
      { field: 'memberInfo', label: '会员信息', placeholder: '输入会员ID/会员昵称/会员手机号', type: 'Input', defaultValue: '' },
      { field: 'sharerAccountStatus', label: '账户状态', placeholder: '请选择', type: 'Select', options: [{ label: '禁用', value: 1 }, { label: '正常', value: 0 }] },
      { field: 'detailType', label: '收入类型', placeholder: '请选择', type: 'Select', options: [{ label: '全部', value: "" },{ label: '月度奖励', value: 1 }, { label: '新人奖励', value: 2 }, { label: '订单佣金', value: 3 },], defaultValue: "" }
    ],
    columns: [
      {
        title: "会员ID",
        dataIndex: "memberId",
        key: "memberId",
      },
      {
        title: "用户昵称",
        dataIndex: "nickName",
        key: "nickName",
      },
      {
        title: "实名姓名",
        dataIndex: "realName",
        key: "realName",
        render: (text) => {
          return text ? text[0] +  "*".repeat(text.length - 1 ) : '未实名'
        }
      },
      {
        title: "会员手机号",
        dataIndex: "memberMobile",
        key: "memberMobile",
        render: (text) => {
          var reg = /^(\d{3})\d{4}(\d{4})$/;
          if (text) {
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        }
      },
      {
        title: "会员状态",
        dataIndex: "memberStatus",
        key: "memberStatus",
        render: (text) => {
          let memberStatus = ''
          switch (text) {
            case 'Y':
              memberStatus = '正常'
              break
            case 'N':
              memberStatus = '冻结'
              break
            default:
              memberStatus = '-'
              break
          }
          return memberStatus
        }
      },
      {
        title: "账户状态",
        dataIndex: "sharerAccountStatusContent",
        key: "sharerAccountStatusContent",
        // render: (text) => {
        //   let sharerAccountStatus = ''
        //   switch (text) {
        //     case 0:
        //       sharerAccountStatus = '正常'
        //       break
        //     case 1:
        //       sharerAccountStatus = '禁用'
        //       break
        //     default:
        //       sharerAccountStatus = '-'
        //       break
        //   }
        //   return sharerAccountStatus
        // }
      },
      {
        title: "现有金额",
        dataIndex: "sharerTotalAvailableAmount",
        key: "sharerTotalAvailableAmount",
        render: (text) => {
          return React.$transNum(text || 0, 2, -2)
        }
      },
      {
        title: "冻结余额",
        dataIndex: "sharerFrozenAmount",
        key: "sharerFrozenAmount",
        render: (text) => {
          return React.$transNum(text || 0, 2, -2)
        }
      },
      {
        title: "可提现余额",
        dataIndex: "sharerAvailableAmount",
        key: "sharerAvailableAmount",
        render: (text) => {
          return React.$transNum(text || 0, 2, -2)
        }
      },
      {
        title: "操作",
        fixed: 'right',
        render: (_, record) => {
          return (
            <div>
              <TheButton haspermi={['distribution:sharerAccount:details']} onClick={() => { this.props.history.push('/distribution/sharerAccount/details/' + record.memberId) }}>详情</TheButton>
              <TheButton haspermi={['distribution:sharerAccount:particulars']} onClick={() => { this.props.history.push('/distribution/sharerAccount/particulars/' + + record.memberId) }}>明细</TheButton>
            </div>
          )
        }
      },
    ],
    dataSource: [],
    pageData: { pageNo: 1, pageSize: 10 },
    total: 0,
    isAddAwardModal: false,//新建月度奖励弹窗、
    addAwardBtnLoading: false,//确认新增月度奖励按钮loading
    sharerValue: null,//分享官id值
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, orderStatus, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'SharerAccount') {
      this.setState({
        queryForm, pageData: { pageNo, pageSize }, orderStatus
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData({ ...queryForm })
      })
    } else {
      this.getData()
    }
  }
  //数据处理
  getData = (values) => {
    let { pageData, queryForm } = this.state
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      let params = { ...pageData, queryForm: this.state.queryForm }
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'SharerAccount', ...params }
      })
      await sharerAccountPage({ ...pageData, ...this.state.queryForm }).then(res => {
        if (res.code === 0) {
          this.setState({
            dataSource: res.data,
            pageData: {
              pageNo: res.pageNo,
              pageSize: res.pageSize
            },
            total: res.totalCount
          })
        }
      })
    })
  }
  //表单值数据处理
  onValuesChange = (value) => {
    if ('sharerId' in value) {
      this.setState({ sharerValue: value.sharerId })
    }
  }
  //查找分相关
  findSharer = async () => {
    let { sharerValue } = this.state
    // this.formRef.setFieldsValue({ sharerName: sharerValue })
    await listByMemberId({ memberId: sharerValue }).then(res => {
      if (res.code === 0) {
        this.formRef.setFieldsValue({ sharerName: null })
        if (res.data === null) {
          message.error('暂无此用户')
        } else {
          if (res.data) {
            if (!res.data.isShardBy) {
              message.error('该用户非高级分享官')
              return
            }
            this.formRef.setFieldsValue({ sharerName: `${res.data.nickName}(${res.data.memberId})` })
          }
        }
      }
    })
  }
  // 确认新建月度奖励
  addAwareSubmit = async (values) => {
    Modal.confirm({
      title: <span style={{ fontSize: 12, fontWeight: 600 }}>核对并确认后，将结算对应金额到该分享官提现账户中</span>,
      icon: null,
      content: <Space direction='vertical'>
        <span>分享官:{values.sharerName}</span>
        <span>奖励金额:{values.estimatedAmount}元</span>
      </Space>,
      onOk: () => {
        this.setState({ addAwardBtnLoading: true }, async () => {
          if (values && values.hasOwnProperty('estimatedAmount')) {
            // values.estimatedAmount = values.estimatedAmount * 100
            values.estimatedAmount = React.$transNum(values.estimatedAmount,0,2)
          }
          await addMonthlyReward({ ...values }).then(res => {
            if (res.code === 0) {
              message.success('月度奖励添加成功!')
              this.cancelAddAward()
              this.getData()
            }
          })
          this.setState({ addAwardBtnLoading: false })
        })
      }
    });
  }
  // 取消新增月度奖励
  cancelAddAward = () => {
    this.setState({ isAddAwardModal: false }, () => {
      this.formRef.resetFields()
    })
  }
  //分页
  pageChange = (pageNo, pageSize) => {
    this.setState({ pageData: { pageNo, pageSize } }, () => {
      this.getData(this.state.queryForm)
    })
  }
  //搜索
  onFormSearch(values) {
    this.setState({ pageData: { pageNo: 1, pageSize: 10 } }, () => {
      this.getData(values)
    })
  }
  //搜索重置
  onReset() {
    this.setState({ queryForm: {} }, () => {
      this.pageChange(1, 10)
    })
  }
  render() {
    const { searchOption, columns, dataSource, pageData: { pageNo, pageSize }, total, addAwardBtnLoading, isAddAwardModal } = this.state
    return (
      <div className='p-layout-box'>
        <TheQueryForm
          ref={(ref) => this.queryFormRef = ref}
          option={searchOption}
          show={true}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)} >
        </TheQueryForm>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 20 }}>
          <TheButton haspermi={['distribution:sharerAccount:addMonthAward']} size='middle' type='primary' onClick={() => { this.setState({ isAddAwardModal: true }) }}>+月度奖励</TheButton>
        </div>
        <TheTable
          scroll={{ x: "max-content", y: '63vh' }}
          columns={columns}
          dataSource={dataSource}
          rowKey={'userId'}
        />
        <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        <Modal title="增加月度奖励" open={isAddAwardModal} footer={null} destroyOnClose onCancel={() => { this.cancelAddAward() }}>
          <Form
            ref={(ref) => this.formRef = ref}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
            onFinish={this.addAwareSubmit}
            onValuesChange={this.onValuesChange}>
            <Form.Item label="查找分享官">
              <Space>
                <Form.Item
                  name="sharerId"
                  noStyle
                  rules={[{ required: true, message: '请查找分享官' }]}
                >
                  <Input style={{ width: 160, }} placeholder="输入用户ID查询" />
                </Form.Item>
                <TheButton type='primary' onClick={() => { this.findSharer() }}>查找</TheButton>
              </Space>
            </Form.Item>
            <Form.Item label="分享官" name='sharerName' rules={[{ required: true, message: '请查找并填充分享官' }]} >
              <Input disabled style={{ color: 'black' }} />
            </Form.Item>
            <Form.Item label="奖励金额" name='estimatedAmount' rules={[{ required: true }]} >
              <InputNumber addonAfter="元" placeholder='请输入金额' max={9999.99} min={0.01} precision={2} />
            </Form.Item>
            <Form.Item label="备注" name='recordComment' rules={[{ required: true }]}>
              <Input maxLength={10} placeholder='1-10字，展示给用户奖励来源' />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
              <Space>
                <Button onClick={() => { this.cancelAddAward() }}>取消</Button>
                <Button type="primary" htmlType="submit" loading={addAwardBtnLoading}>确定</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal >
      </div>
    )
  }
}
